package com.hz.tgb.filter.logtraceid;

import cn.hutool.core.util.IdUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

/**
 * 为异步方法添加traceId
 * @author hezhao created on 2019/12/4 11:37
 */
@Aspect
@Component
public class LogMdcAspect {

    private static final String UNIQUE_ID = "traceId";

    @Pointcut("@annotation(org.springframework.scheduling.annotation.Async) " +
            "|| @annotation(org.springframework.amqp.rabbit.annotation.RabbitListener)")
            // "|| @annotation(org.springframework.cloud.stream.annotation.StreamListener)")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        traceId();
        // 执行方法
        Object result = point.proceed();
        MDC.remove(UNIQUE_ID);
        return result;
    }

    /**
     * 给请求加上traceId
     */
    public static void traceId() {
        MDC.put(LogMdcAspect.UNIQUE_ID, IdUtil.fastSimpleUUID());
    }

}
